package com.baike.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baike.data.Result;
import com.baike.domian.TbTeacherDTO;
import com.baike.em.ConstantEnum;
import com.baike.entity.TbTeacher;
import com.baike.mapper.TbTeacherMapper;
import com.baike.service.ITbTeacherService;
import com.baike.util.MD5Utils;
import com.baike.util.ShiroUtils;
import com.baike.vo.TbTeacherVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-28
 */
@RestController
@RequestMapping("/teacherController")
@Api(value = "教师管理接口")
@RefreshScope //开启自动刷新配置
public class TbTeacherController {

    @Autowired
    private ITbTeacherService teacherService;
    @Autowired
    private TbTeacherMapper tbTeacherMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //教师分页查询
    @GetMapping("findAllPage")
    @ApiOperation(value = "教师查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前页数",required = false,paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = false,paramType = "query")
    })
    public Result<TbTeacher> findAllPage(@RequestParam(defaultValue = "1")Integer pageNum,
                                       @RequestParam(defaultValue = "2")Integer pageSize) {
        Page<TbTeacher> page = new Page<>(pageNum, pageSize, true);//true 为记录总记录数
        IPage<TbTeacher> teacherIPage = tbTeacherMapper.selectPage(page, null);
        //获取的数据集合
        List<TbTeacher> records = teacherIPage.getRecords();
        //创建一个集合
        ArrayList<Object> teacherVOList = new ArrayList<>();
        //遍历获取的集合数据
        for (TbTeacher record : records) {
            //vo类用于前台展示数据脱敏
            TbTeacherVO teacherVO = new TbTeacherVO();
            //把集合中脱敏过的数据转存到VO类中
            BeanUtils.copyProperties(record,teacherVO);
            //添加list集合
            teacherVOList.add(teacherVO);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(teacherVOList);
    }
    //根据条件查询
    @GetMapping("selectLike/{teacherName}")
    @ApiOperation(value = "教师模糊查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherName",value = "教师名称",required = false,paramType = "path")
    })
    public Result<TbTeacher> selectLike(@PathVariable("teacherName")String teacherName){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("teacher_name",teacherName);
        List<TbTeacher> teacherList = tbTeacherMapper.selectList(queryWrapper);
        return Result.build(ConstantEnum.SUCCESS).setResult(teacherList);
    }
    //根据id查询
    @GetMapping("/{teacherId}")
    @ApiOperation(value = "教师条件查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId",value = "教师id",required = true,paramType = "path")
    })
    public Result<TbTeacher> selectById(@PathVariable("teacherId")Long teacherId){
        TbTeacher byId = teacherService.getById(teacherId);
        return Result.build(ConstantEnum.SUCCESS).setResult(byId);
    }

    //教师信息修改
    @PutMapping("/{teacherId}")
    @ApiOperation(value = "教师修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId",value = "教师id",required = true,paramType = "path"),
            @ApiImplicitParam(name = "teacher",value = "教师实体类",required = true,paramType = "body")
    })
    public Result<TbTeacher> update(@RequestBody TbTeacher teacher,@PathVariable("teacherId")Long teacherId){
        teacher.setTeacherId(teacherId);
        int i = tbTeacherMapper.updateById(teacher);
        if (i>0){
            return Result.build(ConstantEnum.UPDATE_SUCCESS);
        }
        return Result.build(ConstantEnum.ERROR);
    }

    //教师批量删除
    @DeleteMapping
    @ApiOperation(value = "教师批量删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "教师id",required = true,paramType = "query")
    })
    public Result<TbTeacher> deleteBatch(@RequestParam("ids")Integer[] ids){


        teacherService.removeByIds(Arrays.asList(ids));
        return Result.build(ConstantEnum.SUCCESS);
    }

    //发送短信接口验证码
//    @ApiOperation(value = "获取注册短信验证码")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "teacherMobile",value = "手机号",required = true,paramType = "query")
//    })
//    @GetMapping(value = "/sendMessage")
//    public Result sendMessage(@RequestParam("teacherMobile") String teacherMobile){
//        //mq生产者发送消息
//        rocketMQTemplate.convertAndSend("phone",teacherMobile);
//        return Result.build(ConstantEnum.CODE_SUCCESS);
//    }

    //增加教师信息(注册)
    @PostMapping(value = "/addRegister",headers="content-type=multipart/form-data")
    @ApiOperation(value = "教师信息增加接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="teacherName",value = "教师名称",required = true,paramType = "query"),
            @ApiImplicitParam(name="teacherPassword",value = "密码",required = true,paramType = "query"),
            @ApiImplicitParam(name="birthday",value = "生日",required = true,paramType = "query"),
            @ApiImplicitParam(name="teacherSex",value = "性别",required = true,paramType = "query"),
            @ApiImplicitParam(name="teacherMobile",value = "手机号",required =true,paramType = "query"),
    })
    public Result addRegister(TbTeacherDTO teacherDTO,
                              @ApiParam(name = "myFile",value = "教师头像",required = true) MultipartFile myFile) throws Exception {
        //先查询数据库是否有存在的教师名称
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("teacher_name",teacherDTO.getTeacherName());
        List<TbTeacher> teacherList = tbTeacherMapper.selectList(queryWrapper);
        if (teacherList.size() <=0){
            Map<String, String> map = upLoadFile(myFile);
            TbTeacher teacher = new TbTeacher();
            BeanUtils.copyProperties(teacherDTO,teacher);
            String s = ShiroUtils.generateSalt(6);
            String md5 = ShiroUtils.encryptPassword("MD5", teacher.getTeacherPassword(), s, 3);
            teacher.setTeacherRegisterTime(new Date());
            //存储所加的盐
            teacher.setSalt(s);
            teacher.setTeacherPassword(md5);
            teacher.setTeacherHead(map.get("imgUrl").toString());
            boolean b = teacherService.save(teacher);
        return Result.build(ConstantEnum.INSERT_SUCCESS).setResult(b);

        }else {
            return Result.build(ConstantEnum.USER_EXIST);
        }

    }
    //上传图片
    public Map<String,String> upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，
        // Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String http = "http://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String buketName = "pengpeng-shop";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t9QoZxwEzGHBPDQHJBu";
        String accessKeySecret = "mJOOC6yd3Qmm96Jx7osQV60AxrtRxK";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 填写网络流地址。
        InputStream inputStream = null;
        try {
            inputStream = myFile.getInputStream();

        } catch (IOException e) {
            e.printStackTrace();
        }

        String fileName = myFile.getOriginalFilename();
        fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));

        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(buketName, fileName, inputStream);

        String url = http + buketName+ "." + endpoint + "/" + fileName;
        // 关闭OSSClient。
        ossClient.shutdown();

        Map<String,String> map = new HashMap<>();
        map.put("imgUrl", url);
        return map;
    }


}
